/**
 * 
 */
package com.zte.claa.inficombo.csa.app.service.sapi.ffhost.mina;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.apache.mina.filter.codec.demux.MessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zte.claa.inficombo.csa.app.util.EdianUtil;
import com.zte.claa.inficombo.csa.app.util.SecurityUtil;

/**
 * @author 0283000115
 *
 */
public class FFTransDevMsgEncoder implements MessageEncoder<FFTransDevMessage> {
	private Logger LOG = LoggerFactory.getLogger(FFTransDevMsgEncoder.class);
	// 字符集
	private Charset charset = null;
	//private CharsetEncoder charsetEncoder = null;

	public FFTransDevMsgEncoder(Charset charset) {
		this.charset = charset;
		if (this.charset == null) {
			this.charset = Charset.forName("UTF-8");
		}
		//this.charsetEncoder = this.charset.newEncoder();
	}

	/**
	 * 编码方法.
	 */
	public void encode(IoSession session, FFTransDevMessage message, ProtocolEncoderOutput out) throws Exception {
		LOG.info("Begin encode message for session: " + session.getId()+", msg: "+message);
		IoBuffer buf = IoBuffer.allocate(FFTransDevMessage.getMinMsgSize(), false).setAutoExpand(true);
		// 1.开头字符.
		buf.put(message.getStartB1());
		buf.put(message.getStartB2());
		// 2.流水号.
		int sno = message.getSno();
		byte[] bs = new byte[]{0, 0, 0, 0};
		EdianUtil.intToByte_LH(sno, bs, 0);
		buf.put(bs[0]);
		buf.put(bs[1]);
		// 3.编码版本号
		buf.put(message.getMainVersion());
		buf.put(message.getUserVersion());
		// 4.时间戳.
		buf.put(message.getSecond());
		buf.put(message.getMinute());
		buf.put(message.getHour());
		buf.put(message.getDay());
		buf.put(message.getMonth());
		buf.put(message.getYear());
		// 5.源地址
		buf.put(message.getSrcAddrBytes());
		// 6.目标地址
		buf.put(message.getDstAddrBytes());
		// 7.应用数据字节长度
		int dateLength = message.getDataLength();
		bs = new byte[]{0, 0, 0, 0};
		EdianUtil.intToByte_LH(dateLength, bs, 0);
		buf.put(bs[0]);
		buf.put(bs[1]);
		// 8.命令字
		buf.put(message.getCmd());
		// 9. 应用数据
		byte[] data = message.getData();
		if(data != null && data.length > 0){
			buf.put(data);
		}
		// 10.校验和
		buf.flip();
		byte[] bsArr = buf.array();
		int len = (bsArr.length < buf.limit()) ? bsArr.length : buf.limit();
		byte[] tmpBs = new byte[len];
		for(int i=0; i<len; i++){
			tmpBs[i] = bsArr[i];
		}
		byte sumChk = SecurityUtil.SumCheck(tmpBs, 2);
		buf = IoBuffer.allocate(tmpBs.length+3, false).setAutoExpand(true);
		buf.put(tmpBs);
		buf.put(sumChk);
		// 11.结束符.
		buf.put(message.getEndB1());
		buf.put(message.getEndB2());
		// 整理buf，准备输出数据
		buf.flip();
		LOG.info("Finish encoding for session: " + session.getId());
		out.write(buf);
		LOG.info("[send data]="+buf.getHexDump());
		buf.free();
		buf = null;
	}

}
